package lx.util;

import javax.net.ssl.*;
import java.io.*;
import java.net.*;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.Map.Entry;

public class ConnectionUrlUtil {
    public static InputStream downFile(String fileUrl) throws IOException {
        URL url = new URL(fileUrl);
        if (fileUrl.startsWith("https")) {
            HttpsURLConnection httpsURLConnection = (HttpsURLConnection) url.openConnection();
            //
            httpsURLConnection.setRequestMethod("GET");
            httpsURLConnection.setConnectTimeout(60 * 1000);
            httpsURLConnection.setReadTimeout(60 * 1000);
            //
            httpsURLConnection.setRequestProperty("Charsert", "UTF-8");
            httpsURLConnection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");//设置参数类型是json格式
            httpsURLConnection.setRequestProperty("Connection", "Keep-Alive");
            httpsURLConnection.setRequestProperty("logType", "base");
            //
            return httpsURLConnection.getInputStream();
        } else {
            URLConnection urlConnection = url.openConnection();
            urlConnection.setConnectTimeout(60 * 1000);
            urlConnection.setReadTimeout(5 * 1000);
            return urlConnection.getInputStream();
        }
    }

    public static String sendPost_3(String url, String parameter) {
        String result = "";
        try {
            URL u0 = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) u0.openConnection();
            conn.setRequestMethod("POST");
            byte contentbyte[] = parameter.toString().getBytes();
            //设置请求类型
            conn.setRequestProperty("Content-Type", "application/json; charset=utf-8");
            //设置表单长度
            conn.setRequestProperty("Content-Length", (new StringBuilder()).append(contentbyte.length).toString());
            //设置默认语言
            conn.setRequestProperty("Content-Language", "en-US");//zh-CN代表中国  默认为美式英语
            conn.setRequestProperty("Accept-Charset", "UTF-8");
            conn.setRequestProperty("contentType", "UTF-8");
            //设置编码

            //连接主机的超时时间（单位：毫秒）
            conn.setConnectTimeout(60000);
            //从主机读取数据的超时时间（单位：毫秒)
            conn.setReadTimeout(60000);
            // Post 请求不能使用缓存
            conn.setUseCaches(false);
            // 设置是否从httpUrlConnection读入，默认情况下是true;
            conn.setDoInput(true);
            // 设置是否向httpUrlConnection输出，因为这个是post请求，参数要放在    2
            // http正文内，因此需要设为true, 默认情况下是false;
            conn.setDoOutput(true);
            BufferedWriter bWriter = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream()));
            bWriter.write(parameter.toString());
            bWriter.flush();
            bWriter.close();
            // 调用HttpURLConnection连接对象的getInputStream()函数,
            // 将内存缓冲区中封装好的完整的HTTP请求电文发送到服务端。
            InputStream in = conn.getInputStream();
            StringBuffer buffer = new StringBuffer();
            for (int i = 0; i != -1;) {
                i = in.read();
                if (i != -1)
                    buffer.append((char) i);
            }
            in.close();
            //此方法是用Reader读取BufferedReader reader = new BufferedReader(new InputStreamReader( connection.getInputStream()));
            result = new String(buffer.toString().getBytes("iso-8859-1"), "UTF-8");
        } catch (Exception ex) {
            System.out.println("sendPost3:"+ex.getMessage());
            //LogUtil.Log(ex.getMessage());
        }
        return result;
    }

    public static String sendPost(String url, String parameter) {
        String result = "";
        try {
            URL u0 = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) u0.openConnection();
            conn.setRequestMethod("POST");
            byte[] contentbyte = parameter.toString().getBytes();
            conn.setRequestProperty("User-Agent",
                    "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
            // 设置请求类型
            conn.setRequestProperty("Content-Type",
                    "application/x-www-form-urlencoded");
            // 设置表单长度
            conn.setRequestProperty("Content-Length", String.valueOf(contentbyte.length));
            // 设置默认语言
            conn.setRequestProperty("Content-Language", "en-US");// zh-CN代表中国
            // 默认为美式英语
            conn.setRequestProperty("Accept-Charset", "utf-8");
            conn.setRequestProperty("contentType", "utf-8");
            // 连接主机的超时时间（单位：毫秒）
            conn.setConnectTimeout(180000);
            // 从主机读取数据的超时时间（单位：毫秒)
            conn.setReadTimeout(180000);
            // Post 请求不能使用缓存
            conn.setUseCaches(false);
            // 设置是否从httpUrlConnection读入，默认情况下是true;
            conn.setDoInput(true);
            // 设置是否向httpUrlConnection输出，因为这个是post请求，参数要放在 2
            // http正文内，因此需要设为true, 默认情况下是false;
            conn.setDoOutput(true);
            BufferedWriter bWriter = new BufferedWriter(new OutputStreamWriter(
                    conn.getOutputStream()));
            bWriter.write(parameter.toString());
            bWriter.flush();
            bWriter.close();
            // 调用HttpURLConnection连接对象的getInputStream()函数,
            // 将内存缓冲区中封装好的完整的HTTP请求电文发送到服务端。
            InputStream in = conn.getInputStream();
            StringBuilder buffer = new StringBuilder();
            for (int i = 0; i != -1; ) {
                i = in.read();
                if (i != -1)
                    buffer.append((char) i);
            }
            in.close();

            // 此方法是用Reader读取BufferedReader reader = new BufferedReader(new
            // InputStreamReader( connection.getInputStream()));
            result = new String(buffer.toString().getBytes(StandardCharsets.ISO_8859_1),
                    StandardCharsets.UTF_8);
        } catch (Exception ex) {
            System.out.println("异常：HTTP POST请求异常" + ex);
            result = "";
        }
        return result;
    }

    public static String sendPostUTF8(String url, String parameter) {
        String result = "";
        try {
            URL u0 = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) u0.openConnection();
            conn.setRequestMethod("POST");
            byte[] contentbyte = parameter.toString().getBytes();
            conn.setRequestProperty("User-Agent",
                    "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
            // 设置请求类型
            conn.setRequestProperty("Content-Type",
                    "application/x-www-form-urlencoded;charset=utf-8");
            // 设置表单长度
            conn.setRequestProperty("Content-Length", String.valueOf(contentbyte.length));
            // 设置默认语言
            conn.setRequestProperty("Content-Language", "en-US");// zh-CN代表中国
            // 默认为美式英语
            conn.setRequestProperty("Accept-Charset", "utf-8");
            conn.setRequestProperty("contentType", "utf-8");
            // 连接主机的超时时间（单位：毫秒）
            conn.setConnectTimeout(180000);
            // 从主机读取数据的超时时间（单位：毫秒)
            conn.setReadTimeout(180000);
            // Post 请求不能使用缓存
            conn.setUseCaches(false);
            // 设置是否从httpUrlConnection读入，默认情况下是true;
            conn.setDoInput(true);
            // 设置是否向httpUrlConnection输出，因为这个是post请求，参数要放在 2
            // http正文内，因此需要设为true, 默认情况下是false;
            conn.setDoOutput(true);
            BufferedWriter bWriter = new BufferedWriter(new OutputStreamWriter(
                    conn.getOutputStream()));
            bWriter.write(parameter.toString());
            bWriter.flush();
            bWriter.close();
            // 调用HttpURLConnection连接对象的getInputStream()函数,
            // 将内存缓冲区中封装好的完整的HTTP请求电文发送到服务端。
            InputStream in = conn.getInputStream();
            StringBuilder buffer = new StringBuilder();
            for (int i = 0; i != -1; ) {
                i = in.read();
                if (i != -1)
                    buffer.append((char) i);
            }
            in.close();

            // 此方法是用Reader读取BufferedReader reader = new BufferedReader(new
            // InputStreamReader( connection.getInputStream()));
            result = new String(buffer.toString().getBytes(StandardCharsets.ISO_8859_1),
                    StandardCharsets.UTF_8);
        } catch (Exception ex) {
            System.out.println("异常：HTTP POST请求异常" + ex);
            result = "";
        }
        return result;
    }

    public static String sendGET(String url, String parameter) {
        String result = "";
        try {
            URL u0 = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) u0.openConnection();
            conn.setRequestMethod("GET");
            byte[] contentbyte = parameter.toString().getBytes();
            conn.setRequestProperty("User-Agent",
                    "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
            // 设置请求类型
            conn.setRequestProperty("Content-Type",
                    "application/x-www-form-urlencoded");
            // 设置表单长度
            conn.setRequestProperty("Content-Length", String.valueOf(contentbyte.length));
            // 设置默认语言
            conn.setRequestProperty("Content-Language", "en-US");// zh-CN代表中国
            // 默认为美式英语
            conn.setRequestProperty("Accept-Charset", "utf-8");
            conn.setRequestProperty("contentType", "utf-8");
            // 连接主机的超时时间（单位：毫秒）
            conn.setConnectTimeout(180000);
            // 从主机读取数据的超时时间（单位：毫秒)
            conn.setReadTimeout(180000);
            // Post 请求不能使用缓存
            conn.setUseCaches(false);
            // 设置是否从httpUrlConnection读入，默认情况下是true;
            conn.setDoInput(true);
            // 设置是否向httpUrlConnection输出，因为这个是post请求，参数要放在 2
            // http正文内，因此需要设为true, 默认情况下是false;
            conn.setDoOutput(true);
            BufferedWriter bWriter = new BufferedWriter(new OutputStreamWriter(
                    conn.getOutputStream()));
            bWriter.write(parameter.toString());
            bWriter.flush();
            bWriter.close();
            // 调用HttpURLConnection连接对象的getInputStream()函数,
            // 将内存缓冲区中封装好的完整的HTTP请求电文发送到服务端。
            InputStream in = conn.getInputStream();
            StringBuilder buffer = new StringBuilder();
            for (int i = 0; i != -1; ) {
                i = in.read();
                if (i != -1)
                    buffer.append((char) i);
            }
            in.close();

            // 此方法是用Reader读取BufferedReader reader = new BufferedReader(new
            // InputStreamReader( connection.getInputStream()));
            result = new String(buffer.toString().getBytes(StandardCharsets.ISO_8859_1),
                    StandardCharsets.UTF_8);
        } catch (Exception ex) {
            System.out.println("异常：HTTP GET请求异常" + ex);
            result = "";
        }
        return result;
    }

    public static String sendPostTest(String url, String parameter, String ip) {
        String result = "";
        HttpURLConnection conn = null;
        try {
            URL u0 = new URL(url);

            if (ip != null) {
                String str[] = ip.split("\\.");
                byte[] b = new byte[str.length];
                for (int i = 0, len = str.length; i < len; i++) {
                    b[i] = (byte) (Integer.parseInt(str[i], 10));
                }
                Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(
                        InetAddress.getByAddress(b), 80)); // b是绑定的ip，生成proxy代理对象，因为http底层是socket实现，
                conn = (HttpURLConnection) u0.openConnection(proxy);
            } else {
                conn = (HttpURLConnection) u0.openConnection();
            }
            conn.setRequestMethod("POST");
            byte[] contentbyte = parameter.toString().getBytes();
            conn.setRequestProperty("User-Agent",
                    "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
            // 设置请求类型
            conn.setRequestProperty("Content-Type",
                    "application/x-www-form-urlencoded");
            // 设置表单长度
            conn.setRequestProperty("Content-Length", String.valueOf(contentbyte.length));
            // 设置默认语言
            conn.setRequestProperty("Content-Language", "en-US");// zh-CN代表中国
            // 默认为美式英语
            conn.setRequestProperty("Accept-Charset", "utf-8");
            conn.setRequestProperty("contentType", "utf-8");

            // 连接主机的超时时间（单位：毫秒）
            conn.setConnectTimeout(180000);
            // 从主机读取数据的超时时间（单位：毫秒)
            conn.setReadTimeout(180000);
            // Post 请求不能使用缓存
            conn.setUseCaches(false);
            // 设置是否从httpUrlConnection读入，默认情况下是true;
            conn.setDoInput(true);
            // 设置是否向httpUrlConnection输出，因为这个是post请求，参数要放在 2
            // http正文内，因此需要设为true, 默认情况下是false;
            conn.setDoOutput(true);
            BufferedWriter bWriter = new BufferedWriter(new OutputStreamWriter(
                    conn.getOutputStream()));
            bWriter.write(parameter.toString());
            bWriter.flush();
            bWriter.close();
            // 调用HttpURLConnection连接对象的getInputStream()函数,
            // 将内存缓冲区中封装好的完整的HTTP请求电文发送到服务端。
            InputStream in = conn.getInputStream();
            StringBuilder buffer = new StringBuilder();
            for (int i = 0; i != -1; ) {
                i = in.read();
                if (i != -1)
                    buffer.append((char) i);
            }
            in.close();

            // 此方法是用Reader读取BufferedReader reader = new BufferedReader(new
            // InputStreamReader( connection.getInputStream()));
            result = new String(buffer.toString().getBytes(StandardCharsets.ISO_8859_1),
                    StandardCharsets.UTF_8);
        } catch (Exception ex) {
            System.out.println("异常：HTTP POST sendPostTest请求异常" + ex);
            result = "";
        }
        return result;
    }

    public static String http(String url, Map<String, String> params) {
        URL u = null;
        HttpURLConnection con = null;
        // 构建请求参数
        StringBuilder sb = new StringBuilder();
        if (params != null) {
            for (Entry<String, String> e : params.entrySet()) {
                sb.append(e.getKey());
                sb.append("=");
                sb.append(e.getValue());
                sb.append("&");
            }
            sb.substring(0, sb.length() - 1);
        }
        // 尝试发送请求
        try {
            u = new URL(url);
            con = (HttpURLConnection) u.openConnection();
            con.setRequestMethod("POST");
            con.setDoOutput(true);
            con.setDoInput(true);
            con.setUseCaches(false);
            con.setRequestProperty("Content-Type",
                    "application/x-www-form-urlencoded");
            OutputStreamWriter osw = new OutputStreamWriter(
                    con.getOutputStream(), StandardCharsets.UTF_8);
            osw.write(sb.toString());
            osw.flush();
            osw.close();
        } catch (Exception e) {
            System.out.println("异常：HTTP http请求异常" + e);
        } finally {
            if (con != null) {
                con.disconnect();
            }
        }

        // 读取返回内容
        StringBuilder buffer = new StringBuilder();
        try {
            assert con != null;
            BufferedReader br = new BufferedReader(new InputStreamReader(
                    con.getInputStream(), StandardCharsets.UTF_8));
            String temp;
            while ((temp = br.readLine()) != null) {
                buffer.append(temp);
                buffer.append("\n");
            }
        } catch (Exception e) {
            System.out.println("异常：HTTP POST http请求异常" + e);
        }

        return buffer.toString();
    }

    public static String sendPostGB(String url, String parameter) {
        String result = "";
        try {
            URL u0 = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) u0.openConnection();
            conn.setRequestMethod("POST");
            byte[] contentbyte = parameter.toString().getBytes();
            conn.setRequestProperty("User-Agent",
                    "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
            // 设置请求类型
            conn.setRequestProperty("Content-Type",
                    "application/x-www-form-urlencoded");
            // 设置表单长度
            conn.setRequestProperty("Content-Length", String.valueOf(contentbyte.length));
            // 设置默认语言
            conn.setRequestProperty("Content-Language", "en-US");// zh-CN代表中国
            // 默认为美式英语
            conn.setRequestProperty("Accept-Charset", "GB18030");
            conn.setRequestProperty("contentType", "GB18030");
            // 连接主机的超时时间（单位：毫秒）
            conn.setConnectTimeout(180000);
            // 从主机读取数据的超时时间（单位：毫秒)
            conn.setReadTimeout(180000);
            // Post 请求不能使用缓存
            conn.setUseCaches(false);
            // 设置是否从httpUrlConnection读入，默认情况下是true;
            conn.setDoInput(true);
            // 设置是否向httpUrlConnection输出，因为这个是post请求，参数要放在 2
            // http正文内，因此需要设为true, 默认情况下是false;
            conn.setDoOutput(true);
            BufferedWriter bWriter = new BufferedWriter(new OutputStreamWriter(
                    conn.getOutputStream()));
            bWriter.write(parameter.toString());
            bWriter.flush();
            bWriter.close();
            // 调用HttpURLConnection连接对象的getInputStream()函数,
            // 将内存缓冲区中封装好的完整的HTTP请求电文发送到服务端。
            InputStream in = conn.getInputStream();
            StringBuilder buffer = new StringBuilder();
            for (int i = 0; i != -1; ) {
                i = in.read();
                if (i != -1)
                    buffer.append((char) i);
            }
            in.close();

            // 此方法是用Reader读取BufferedReader reader = new BufferedReader(new
            // InputStreamReader( connection.getInputStream()));
            result = new String(buffer.toString().getBytes(StandardCharsets.ISO_8859_1),
                    StandardCharsets.UTF_8);
        } catch (Exception ex) {
            System.out.println("异常：HTTP POST请求异常" + ex);
            result = "";
        }
        return result;
    }
}
